package com.easyhouse.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@Service
public class DingdingService {
    @Autowired
    private RestTemplate restTemplate;

    private static String URL = "https://oapi.dingtalk.com/robot/send?access_token=5fcb1da7f2a49db1367a03155abec2a982bc6661bc677108d6862a263c64e7a0";

    public static String getExt(){
        String secret = "SEC0e133d66f261161695a5937f5760bba8e3cbf37e159a21108841ccf1d5a350d2";
        Long timestamp = System.currentTimeMillis();
        String stringToSign = timestamp + "\n" + secret;
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = new String(Base64.encodeBase64(signData));
            String url=URL+"&timestamp="+timestamp+"&sign="+sign;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    public void sent(String msg){
        Map<String,Object> json=new HashMap();
        Map<String,Object> text=new HashMap();
        json.put("msgtype","markdown");
        json.put("markdown",text);
        text.put("text","#### 今日售房信息： \n> 2020年十一月十九号\n> ![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png)\n> ###### 10点20分发布 [价格](http://42.192.23.95) \n"+msg);
        text.put("title","数据汇总");
        String forObject = restTemplate.postForObject(getExt(),json, String.class);
        System.out.println(forObject);
    }
}
